package com.gitee.zzh.common.jwt;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JwtToken {
    private static final String SECRET = "!!@#$kk2s";

    /**
     * 根据验证码生成token
     */
    public static String createToken(String checkCode, int seconds) {
        Calendar nowTime = Calendar.getInstance();
        nowTime.add(Calendar.SECOND, seconds);
        Date expiresDate = nowTime.getTime();
        Map<String, Object> map = new HashMap<>();
        map.put("alg", "HMAC256");
        map.put("typ", "JWT");
        return JWT.create().withHeader(map)
                .withClaim("checkCode", checkCode)
                .withExpiresAt(expiresDate)
                .withIssuedAt(new Date())
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 校验token并返回载体数据
     */
    public static Map<String, Claim> verifyToken(String token) {
        JWTVerifier verifier = JWT.require(Algorithm.HMAC256(SECRET)).build();
        try {
            DecodedJWT jwt = verifier.verify(token);
            return jwt.getClaims();
        } catch (TokenExpiredException ex) {
            return new HashMap<>();
        }
    }

    /**
     * 根据token并返回验证码，返回""说明验证码已过期
     */
    public static String getCheckCode(String token) {
        Claim claim = verifyToken(token).get("checkCode");
        return claim == null? "" : verifyToken(token).get("checkCode").asString();
    }

}
